import { Table, message, Row, Col, Space, Tooltip, InputNumber } from "antd";
import { useModel, history } from "umi";
import { Card as SemiCard, ButtonGroup, Button, List } from "@douyinfe/semi-ui";
import { IconRefresh, IconEyeOpened } from "@douyinfe/semi-icons";
import { useEffect } from "react";

import useOrganizationCustomer from "../hooks/useOrganizationCustomer";
import useWaitExamineAuthorize from "../hooks/useWaitExamineAuthorize";

const OrganizationCustomerPage = () => {
    const { windowInnerHeight } = useModel("global");
    const { loadCustomers, dataLoading, customers, selectedCustomer, setSelectedCustomer } = useOrganizationCustomer();

    useEffect(() => {
        loadCustomers();
    }, []);

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 54;

    return (
        <Row gutter={10} style={{ padding: 10 }}>
            <Col span={5}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 15 }}>组织用户列表</span>}
                    headerStyle={{ padding: "10px 14px" }}
                    shadows="always"
                    bordered={false}
                    size="default"
                    bodyStyle={{ padding: 1, height: cardBodyHeight, overflow: "auto" }}
                    headerExtraContent={
                        <ButtonGroup>
                            <Button icon={<IconRefresh />} onClick={loadCustomers}></Button>
                        </ButtonGroup>
                    }
                >
                    <List
                        loading={dataLoading}
                        dataSource={customers}
                        renderItem={(item, index) => {
                            return (
                                <List.Item
                                    key={index}
                                    className={`list-item ${selectedCustomer?.oiUuid === item?.oiUuid ? "list-item-selected" : ""}`}
                                    main={<div>{item.oiName || "-"}</div>}
                                    onClick={() => setSelectedCustomer(item)}
                                ></List.Item>
                            );
                        }}
                    />
                </SemiCard>
            </Col>
            <Col span={19}>
                <SemiCard
                    title={
                        <Space size={30}>
                            <span style={{ lineHeight: "32px", fontSize: 15 }}>{selectedCustomer?.oiName}</span>
                        </Space>
                    }
                    headerStyle={{ padding: "10px 14px" }}
                    shadows="always"
                    bordered={false}
                    size="default"
                    bodyStyle={{ padding: 10, height: cardBodyHeight, overflow: "auto" }}
                >
                    <AuthorizeRoles selectedCustomer={selectedCustomer} />

                    <div style={{ height: 10 }}></div>

                    <AuthorizeRecords selectedCustomer={selectedCustomer} />
                </SemiCard>
            </Col>
        </Row>
    );
};

const AuthorizeRoles = ({ selectedCustomer }) => {
    const { UTCTimeToLocal } = useModel("global");
    const { loadAuthorizeRoles, dataLoading, authorizeRoles } = useOrganizationCustomer();

    const loadData = () => {
        selectedCustomer?.oiUuid && loadAuthorizeRoles(selectedCustomer.oiUuid);
    };

    useEffect(() => {
        loadData();
    }, [selectedCustomer]);

    let Title = () => (
        <div className="flex-box" style={{ lineHeight: "32px" }}>
            <div>{"授权的角色列表"}</div>
            <div>
                <ButtonGroup>
                    <Button icon={<IconRefresh />} onClick={loadData} />
                </ButtonGroup>
            </div>
        </div>
    );

    return (
        <Table loading={dataLoading} size="small" title={Title} bordered dataSource={authorizeRoles} rowKey="oaarRole" pagination={false}>
            <Table.Column title="序号" align="center" width={60} render={(_, r, i) => i + 1} />
            <Table.Column title="角色名称" dataIndex="oaarRole" align="left" render={(_, r, i) => <a onClick={() => history.replace("/application_organization/by_role", { roleName: _ })}>{_}</a>} />
            <Table.Column title="服务商名称" dataIndex="oiName" align="left" render={(_, r, i) => <a onClick={() => history.replace("/servicer/authed_roles", { spUuid: r.spUuid })}>{_}</a>} />
            <Table.Column title="最近授权时间" dataIndex="oaarTime" align="center" width={160} render={(_, r, i) => UTCTimeToLocal(_)} />
            <Table.Column title="授权的总月数" dataIndex="oaarMont" align="center" width={120} />
            <Table.Column title="授权方式" dataIndex="oaarType" align="center" width={100} />
            <Table.Column title="授权开始日期" dataIndex="oaarStda" align="center" width={120} />
            <Table.Column title="授权结束日期" dataIndex="oaarEnda" align="center" width={120} />
        </Table>
    );
};

const AuthorizeRecords = ({ selectedCustomer }) => {
    const { UTCTimeToLocal } = useModel("global");
    const { loadAuthorizeRecords, dataLoading, authorizeRecords } = useOrganizationCustomer();
    const { updateRealityPrice } = useWaitExamineAuthorize();

    const loadData = () => {
        selectedCustomer?.oiUuid && loadAuthorizeRecords(selectedCustomer.oiUuid);
    };

    useEffect(() => {
        loadData();
    }, [selectedCustomer]);

    const savePrice = async (record, values) => {
        let variables = {
            oaaaUuid: record.oaaaUuid,
            ...values,
        };
        updateRealityPrice(variables, (res) => {
            if (res) {
                message.success("更新成功");
                loadData();
            }
        });
    };

    let Title = () => (
        <div className="flex-box" style={{ lineHeight: "32px" }}>
            <div>{"授权的历史记录"}</div>
            <div>
                <ButtonGroup>
                    <Button icon={<IconRefresh />} onClick={loadData} />
                </ButtonGroup>
            </div>
        </div>
    );

    let renderSdRepr = (_, r, i) => (
        <InputNumber
            controls={false}
            prefix="￥"
            value={_}
            onPressEnter={(e) => {
                savePrice(r, { sdRepr: parseFloat(e.target.value) });
            }}
            style={{ width: "100%" }}
        />
    );

    let renderSpRepr = (_, r, i) => (
        <InputNumber
            controls={false}
            prefix="￥"
            value={_}
            onPressEnter={(e) => {
                savePrice(r, { spRepr: parseFloat(e.target.value) });
            }}
            style={{ width: "100%" }}
        />
    );

    return (
        <Table loading={dataLoading} size="small" title={Title} bordered dataSource={authorizeRecords} rowKey="oaaaUuid" pagination={false}>
            <Table.Column title="序号" align="center" width={60} render={(_, r, i) => i + 1} />
            <Table.Column title="授权的角色" dataIndex="oaaaRole" align="left" render={(_, r, i) => _.join(", ")} />
            <Table.Column title="服务商名称" dataIndex="oiName" align="left" />
            <Table.Column title="授权的月数" dataIndex="oaaaMont" align="center" width={100} />
            <Table.Column title="授权方式" dataIndex="oaaaType" align="center" width={80} />
            <Table.ColumnGroup title="开发商结算">
                <Table.Column title="参考结算" dataIndex="oaaaSdpr" align="right" width={100} render={(_, r, i) => "￥" + helper.numberFormat(_, 0)} />
                <Table.Column title="实际结算" dataIndex="sdRepr" align="right" width={120} render={renderSdRepr} />
            </Table.ColumnGroup>
            <Table.ColumnGroup title="服务商结算">
                <Table.Column title="参考结算" dataIndex="oaaaSppr" align="right" width={100} render={(_, r, i) => "￥" + helper.numberFormat(_, 0)} />
                <Table.Column title="实际结算" dataIndex="spRepr" align="right" width={120} render={renderSpRepr} />
            </Table.ColumnGroup>
            <Table.Column title="客户结算" dataIndex="oaaaEcpr" align="right" width={80} render={(_, r, i) => "￥" + helper.numberFormat(_, 0)} />
            <Table.Column title="申请时间" dataIndex="oaaaTime" align="center" width={80} render={(_, r, i) => <Tooltip title={UTCTimeToLocal(_)}>{<IconEyeOpened />}</Tooltip>} />
            <Table.Column title="审核状态" dataIndex="oaaaExst" align="center" width={80} />
        </Table>
    );
};

export default OrganizationCustomerPage;
